<template>
  <el-dialog :close-on-click-modal="false" :title="form.id ? $t('common.editBtn') : $t('common.addBtn')" width="80%"
             draggable v-model="visible">
    <el-card header="基础信息" shadow="never">
      <el-form :model="form" :rules="dataRules" label-width="90px" ref="dataFormRef" v-loading="loading">
        <!-- 学校选择 - 新增时支持多选，编辑时单选 -->
        <el-form-item label="选择学校" prop="schoolIdList" v-if="!form.id">
          <el-select
            v-model="form.schoolIdList"
            multiple
            placeholder="请选择学校（可多选）"
            style="width: 100%"
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option
              v-for="item in schoolList"
              :key="item.id"
              :label="item.schoolName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学校" v-else>
          <el-input
            :value="getCurrentSchoolName()"
            disabled
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="子菜名称" prop="dishName">
          <el-input v-model="form.dishName" placeholder="请输入套餐子菜名称，多个子菜用+分隔，如:麻婆豆腐+鱼香肉丝"
                    style="width: 100%"/>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="套餐图片" prop="pics">
          <ImageUpload v-model:imageUrl="form.pics" borderRadius="20px">
            <template #empty>
              <span>请上传套餐图片</span>
            </template>
          </ImageUpload>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card header="营养成分" shadow="never" style="margin-top: 10px">
      <el-button type="primary" @click="handlerAddDes">添加</el-button>
      <el-table :data="data.desList">
        <el-table-column prop="name" label="菜名">
          <template #default="scope">
            <el-input type="textarea" :rows="1" v-model="scope.row.name" placeholder="请输入菜名"/>
          </template>
        </el-table-column>
        <el-table-column label="配料" prop="batching">
          <template #default="scope">
            <el-input type="textarea" :rows="1" v-model="scope.row.batching" placeholder="请输入配料"/>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="热量">
          <template #default="scope">
            <el-input v-model="scope.row.quantity" placeholder="请输入热量"/>
          </template>
        </el-table-column>
        <el-table-column prop="protein" label="蛋白质">
          <template #default="scope">
            <el-input v-model="scope.row.protein" placeholder="请输入蛋白质含量"/>
          </template>
        </el-table-column>
        <el-table-column prop="fat" label="脂肪">
          <template #default="scope">
            <el-input v-model="scope.row.fat" placeholder="请输入脂肪含量"/>
          </template>
        </el-table-column>
        <el-table-column prop="vitaminC" label="维生素C">
          <template #default="scope">
            <el-input v-model="scope.row.vitaminC" placeholder="请输入维生素C含量"/>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注">
          <template #default="scope">
            <el-input v-model="scope.row.notes" placeholder="请输入备注"/>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="mini" @click="()=>data.desList.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button @click="onSubmit" type="primary" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			  <el-button v-if="form.id" @click="handleDelete([form.id])" type="danger" >删除</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="systemRoleDialog" setup>
import {useMessage, useMessageBox} from '/src/hooks/message';
import {addObj, getObj, putObj,delObj} from '/src/api/school/dateCombo';
import {listAll as listAllSchool} from '/src/api/school/school';
import {useI18n} from 'vue-i18n';

const ImageUpload = defineAsyncComponent(() => import('/@/components/Upload/Image.vue'));
const Editor = defineAsyncComponent(() => import('/@/components/Editor/index.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const {t} = useI18n();

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const schoolList = ref([]);
const data = reactive({
  desList: []
})

// 提交表单数据
const form = reactive({
  id: '',
  comboId: '',
  schoolId: '',
  schoolIdList: [], // 新增时的多选学校
  date: '',
  dishName: '',
  pics: '',
  descption: ''
});

// 定义校验规则
const dataRules = computed(() => {
  const rules: any = {
    dishName: [
      {required: true, message: '名称不能为空', trigger: 'blur'},
    ],
    pics: [
      {required: true, message: '菜品图片不能为空', trigger: 'blur'},
    ],
    date: [
      {required: true, message: '日期不能为空', trigger: 'blur'},
    ]
  };

  // 新增模式下需要校验学校选择
  if (!form.id) {
    rules.schoolIdList = [
      {required: true, message: '请选择学校', trigger: 'change'},
    ];
  }

  return rules;
});

// 获取学校列表
const getSchoolList = async () => {
  try {
    const resp = await listAllSchool();
    schoolList.value = resp.data;
  } catch (error) {
    console.error('获取学校列表失败:', error);
    useMessage().error('获取学校列表失败');
  }
};

// 获取当前学校名称（编辑时显示）
const getCurrentSchoolName = () => {
  const school = schoolList.value.find(item => item.id === form.schoolId);
  return school ? school.schoolName : '';
};

// 打开弹窗
const openDialog = (comboId: string, id: string, schoolId: string) => {
  visible.value = true;
  form.id = '';
  form.comboId = comboId;
  form.schoolId = schoolId;
  form.schoolIdList = [];
  data.desList = [];

  // 获取学校列表
  getSchoolList();

  nextTick(() => {
    dataFormRef.value.resetFields();
  });

  // 获取角色信息
  if (id) {
    form.id = id;
    getRoleData(id);
  }

};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.descption = JSON.stringify(data.desList);

    if (form.id) {
      // 编辑模式：只更新单个套餐
      await putObj(form);
      useMessage().success(t('common.editSuccessText'));
    } else {
      // 新增模式：为每个选中的学校创建套餐
      if (!form.schoolIdList || form.schoolIdList.length === 0) {
        useMessage().error('请选择至少一个学校');
        return;
      }

      // 批量创建套餐
      const promises = form.schoolIdList.map(schoolId => {
        const comboData = {
          comboId: form.comboId,
          schoolId: schoolId,
          date: form.date,
          dishName: form.dishName,
          pics: form.pics,
          descption: form.descption
        };
        return addObj(comboData);
      });

      await Promise.all(promises);
      useMessage().success(`成功为 ${form.schoolIdList.length} 个学校创建套餐`);
    }

    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};
// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm(t('common.delConfirmText'));
  } catch {
    return;
  }

  try {
    await delObj(ids);
    emit('refresh')
    visible.value = false;
    useMessage().success(t('common.delSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

const handlerAddDes = () => {
  data.desList.push({
    name: '',
    batching: '',
    quantity: '',
    protein: '',
    fat: '',
    vitaminC: '',
    notes: ''
  })
}

// 初始化角色数据
const getRoleData = (id: string) => {
  // 获取部门数据
  getObj(id).then((res: any) => {
    Object.assign(form, res.data);
    if (res.data.descption) {
      data.desList = JSON.parse(res.data.descption)
    }
  });
};


// 暴露变量
defineExpose({
  openDialog,
});
</script>
